package com.custom.base.view

import android.content.Context
import android.util.AttributeSet
import com.custom.base.R

class CheckBoxImageView(context: Context, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatImageView(context, attrs) {
    private var imageY = 0
    private var imageN = 0
    private var listener:OnClickListener? = null
    var check = true
        get() = field
        set(value) {
            field = value
            update()
        }
    init {
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.CheckBoxImageView)
        attributes.apply {
            imageY = getResourceId(R.styleable.CheckBoxImageView_checkboxStyle_yid,0)
            imageN = getResourceId(R.styleable.CheckBoxImageView_checkboxStyle_nid,0)
            check = getBoolean(R.styleable.CheckBoxImageView_checkboxStyle_check,true)
        }
        update()

        adjustViewBounds = true

        setOnClickListener {
            check = !check
            update()
            listener?.onClick(check)
        }
    }

    private fun update(){
        if(check){
            if(imageY!=0) setImageResource(imageY)
        }else{
            if(imageN!=0) setImageResource(imageN)
        }
    }

    fun setOnClickListener(listener:OnClickListener){
        this.listener = listener
    }

    interface OnClickListener{
        fun onClick(check:Boolean)
    }
}